import InboundPlanApi from '../../../common/api/breed/inboundplan.api.js';
import { DictionaryType, requestDict } from '../../../common/dictionary/dictionary-type.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../../common/api/file-request.js';
import doT from '../../../../vendor/template/doT.js';

const addPlaceTypeTemplate = doT.template($('#addPlaceType-template').text());

(function (window, document, $) {
    let _vm;
    let openId = Utils.GetSessionStorage('openId');
    let SNAccountEply = JSON.parse(Utils.GetSessionStorage('SNAccountEply'));
    console.log(SNAccountEply);
    let inboundPlanPlaceInfo = {},
        placeTypeList = [];
    let id = '';
    let historyObj = JSON.parse(Utils.GetSessionStorage('perinplanList'));
    let opType = historyObj?.opType || '';

    $(async function () {
        id = getUrlKey('id');

        _vm = new Vue({
            el: '#addentryrgst-form',
            data() {
                return {
                    name: SNAccountEply?.name,
                    numCode: SNAccountEply?.numCode,
                    sex: '男',
                    phoneNum: '',
                    farmOrg: {
                        id: '',
                        name: '',
                    },
                    planDate: '',
                    isolationDate: '',
                    departTime: '',
                    attachments: '',
                    trip: '',
                    belongings: [],
                    placeType: '',
                    isTrans: false,
                    departureFactory: {
                        id: '',
                        name: '',
                    },
                    departureDate: '',
                    attaches: [],
                    images: [],
                    uploadCount: 0,
                };
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        await initSelectValue();
        if (id || opType == 2) {
            _ediCommand();
        }
        _initCommand();
        clickFun();
        uploadInit();
    });

    // 编辑操作
    const _ediCommand = async () => {
        if (Utils.IsNotNull(id)) {
            $('title').text('人员入厂-编辑');
            await InboundPlanApi.getDetailPerInPlan(id).then((result) => {
                let personObj = result.person;
                _vm.farmOrg.id = result.destFarm.id;
                _vm.farmOrg.name = result.destFarm.name;
                _vm.planDate = Utils.IsNotNull(result.planDate) ? result.planDate.split(' ')[0].replace(/\//g, '-') : '';
                _vm.belongings = personObj.belongings;
                _vm.name = personObj.name;
                _vm.phoneNum = personObj.phoneNumber;
                _vm.numCode = personObj.numCode;
                _vm.departTime = Utils.IsNotNull(personObj.departTime) ? personObj.departTime.split(' ')[0].replace(/\//g, '-') : '';
                _vm.isolationDate = Utils.IsNotNull(personObj.isolationDate) ? personObj.isolationDate.split(' ')[0].replace(/\//g, '-') : '';
                _vm.trip = personObj.tripDetail;
                _vm.departureDate = Utils.IsNotNull(personObj.sourceDepartTime) ? personObj.sourceDepartTime.split(' ')[0].replace(/\//g, '-') : '';
                _vm.departureFactory.id = personObj.sourceFarm?.id || '';
                _vm.departureFactory.name = personObj.sourceFarm?.name || '';
                _vm.sex = personObj.gender == 1 ? '男' : '女';
                _vm.placeType = personObj.placeType;
                let placeTypeEditList = personObj.placeType.includes(',') ? personObj.placeType.split(',') : [personObj.placeType];
                $('input[name="sex"][value="' + _vm.sex + '"]').prop('checked', true);
                placeTypeEditList.forEach((s) => {
                    $(`#placeTypeTrue${s}`).prop('checked', true);
                });

                $('#farmOrg').setSelectValue(_vm.farmOrg.id, _vm.farmOrg.name);
                if (_vm.departureFactory.id && _vm.departureFactory.name) {
                    $('#isTrans').prop('checked', true);
                    $('#isTrans').change();
                    $('#departureFactory').setSelectValue(_vm.departureFactory.id, _vm.departureFactory.name);
                    $('#isTransDiv').css('display', 'block');
                } else {
                    $('#isTrans').prop('checked', false);
                    $('#isTrans').change();
                    $('#isTransDiv').css('display', 'none');
                }
                _vm.attachments = personObj.attachments;
            });
        }
        if (opType == 2) {
            let personObj = historyObj.person;
            _vm.farmOrg.id = historyObj.destFarm.id;
            _vm.farmOrg.name = historyObj.destFarm.name;
            _vm.planDate = Utils.IsNotNull(historyObj.planDate) ? historyObj.planDate.split(' ')[0].replace(/\//g, '-') : '';
            _vm.belongings = personObj.belongings;
            _vm.name = personObj.name;
            _vm.phoneNum = personObj.phoneNumber;
            _vm.numCode = personObj.numCode;
            _vm.departTime = Utils.IsNotNull(personObj.departTime) ? personObj.departTime.split(' ')[0].replace(/\//g, '-') : '';
            _vm.isolationDate = Utils.IsNotNull(personObj.isolationDate) ? personObj.isolationDate.split(' ')[0].replace(/\//g, '-') : '';
            _vm.departureDate = Utils.IsNotNull(personObj.sourceDepartTime) ? personObj.sourceDepartTime.split(' ')[0].replace(/\//g, '-') : '';
            _vm.trip = personObj.tripDetail;
            _vm.departureFactory.id = personObj.sourceFarm?.id || '';
            _vm.departureFactory.name = personObj.sourceFarm?.name || '';
            _vm.sex = personObj.gender == 1 ? '男' : '女';
            _vm.placeType = personObj.placeType;
            let placeTypeEditList = personObj.placeType.includes(',') ? personObj.placeType.split(',') : [personObj.placeType];
            $('input[name="sex"][value="' + _vm.sex + '"]').prop('checked', true);
            placeTypeEditList.forEach((s) => {
                $(`#placeTypeTrue${s}`).prop('checked', true);
            });

            $('#farmOrg').setSelectValue(_vm.farmOrg.id, _vm.farmOrg.name);
            if (_vm.departureFactory.id && _vm.departureFactory.name) {
                $('#isTrans').prop('checked', true);
                $('#isTrans').change();
                $('#departureFactory').setSelectValue(_vm.departureFactory.id, _vm.departureFactory.name);
                $('#isTransDiv').css('display', 'block');
            } else {
                $('#isTrans').prop('checked', false);
                $('#isTrans').change();
                $('#isTransDiv').css('display', 'none');
            }
            _vm.attachments = personObj.attachments;
        }
    };

    // 初始化数据
    const _initCommand = async () => {
        // 是否转厂
        $('#isTrans').on('change', function (e) {
            // 根据状态执行不同操作
            if (e.target.checked) {
                // 开关打开时的逻辑
                $('#isTransDiv').css('display', 'block');
                _vm.isTrans = true;
            } else {
                // 开关关闭时的逻辑
                $('#isTransDiv').css('display', 'none');
                _vm.isTrans = false;
            }
        });

        // 上传附件
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 10) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });

        // 选择日期
        $('#search-isolationDate').on('click', function () {
            pickIsolationDate();
        });
        // 选择日期
        $('#search-departureDate').on('click', function () {
            pickDepartureDate();
        });
        // 选择日期
        $('#search-planDate').on('click', function () {
            pickPlanDate();
        });
        // 选择日期
        $('#search-departTime').on('click', function () {
            pickDepartTime();
        });
    };

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            history.go(-1);
        });

        // 下一步
        $('#btnSaveNext').on('click', async function (e) {
            if (!Utils.IsNotNull(_vm.name)) {
                return $.toptip(`请输入姓名!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.phoneNum)) {
                return $.toptip(`请输入电话号码!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.isolationDate)) {
                return $.toptip(`请选择隔离日期!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.trip)) {
                return $.toptip(`请输入行程!`, 'warning');
            }
            if (_vm.isTrans == true && !Utils.IsNotNull(_vm.departureFactory.id) && !Utils.IsNotNull(_vm.departureDate)) {
                return $.toptip(`请选择出发厂和离厂日期!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.farmOrg.id)) {
                return $.toptip(`请选择目的地!`, 'warning');
            }
            // 电话号码
            const PHONE_VERIFICATION = /^1[3456789]\d{9}$/;
            if (!PHONE_VERIFICATION.test(_vm.phoneNum)) {
                return $.toptip(`请输入正确的电话号码`, 'warning');
            }
            // 入厂计划查询人员入厂是否允许
            let flag = null;
            if (_vm.isTrans) {
                let query = {
                    sourceFarmId: _vm.departureFactory.id,
                    destFarmId: _vm.farmOrg.id,
                    sourceDepartTime: _vm.departureDate,
                    isolationDate: _vm.isolationDate,
                };
                await InboundPlanApi.postVisible(query)
                    .then((result) => {
                        let res = JSON.parse(result);
                        if (res?.isSucceed == false) {
                            flag = false;
                            return $.toptip(`${res?.msg}`, 'error');
                        } else {
                            if (res?.data == false) {
                                flag = false;
                                return $.toptip(`${res?.msg}`, 'warning');
                            }
                        }
                    })
                    .catch((error) => {
                        let err = JSON.parse(error.responseText);
                        flag = false;
                        return $.toptip(`${err?.msg}`, 'error');
                    });
            }
            if (flag == false) return;

            let params = {
                type: 1, // 人员入厂
                destFarm: {
                    id: _vm.farmOrg.id,
                    name: _vm.farmOrg.name,
                },
                planDate: _vm.isolationDate,
                deliverySeq: 0,
                opType: 1,
                person: {
                    name: _vm.name,
                    gender: $('input[name="sex"]:checked').val() == '男' ? 1 : 2,
                    phoneNumber: _vm.phoneNum,
                    numCode: _vm.numCode,
                    isolationDate: _vm.isolationDate,
                    tripDetail: _vm.trip,
                    belongings: _vm.belongings,
                    placeType: _vm.placeType,
                    departTime: _vm.isolationDate,
                    attachments: _vm.attachments,
                    sourceFarm: {
                        id: _vm.departureFactory.id || '',
                        name: _vm.departureFactory.name || '',
                    },
                    sourceDepartTime: _vm.departureDate || '',
                    // "checkinInfo": {
                    //     "location": "string",
                    //     "time": "2025-06-09T09:38:49.924Z"
                    // },
                    unionId: openId,
                    openId: openId,
                },
                materials: null,
                car: null,
                remark: '',
                billStatus: 1, // 保存传1 保存并提交传2
            };
            let isTrans = $('#isTrans').is(':checked');
            if (isTrans == false) {
                params.person.sourceFarm = null;
                params.person.sourceDepartTime = null;
            }
            window.sessionStorage.removeItem('perinplanList');
            Utils.SetSessionStorage('perinplanList', params);
            location.href = `../inboundplan/addperinplantwo.html?v=${Utils.GetTime()}&id=${id}`;
        });

        // 保存并提交
        $('#btnSaveSubmit').on('click', function (e) {
            if (!Utils.IsNotNull(_vm.name)) {
                return $.toptip(`请输入姓名!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.phoneNum)) {
                return $.toptip(`请输入电话号码!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.isolationDate)) {
                return $.toptip(`请选择隔离日期!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.trip)) {
                return $.toptip(`请输入行程!`, 'warning');
            }
            if (_vm.isTrans == true && !Utils.IsNotNull(_vm.departureFactory.id) && !Utils.IsNotNull(_vm.departureDate)) {
                return $.toptip(`请选择出发厂和离厂日期!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.farmOrg.id)) {
                return $.toptip(`请选择目的地!`, 'warning');
            }
            // 电话号码
            const PHONE_VERIFICATION = /^1[3456789]\d{9}$/;
            if (!PHONE_VERIFICATION.test(_vm.phoneNum)) {
                return $.toptip(`请输入正确的电话号码`, 'warning');
            }
            savetips(2);
        });
    };
    // 保存
    const savetips = (type = 1) => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;"><div class="addentry">是否确认保存并提交该单据？</div></div></div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '确定',
                    onClick: function () {
                        $.closeModal();
                        let placeTypeNewList = [];
                        placeTypeList.forEach((s) => {
                            let name = `placeType${s}`;
                            // 获取选中的单选框的值
                            let selectedValue = $('input[name="' + name + '"]:checked').val();
                            if (selectedValue == 'true') {
                                placeTypeNewList.push($('input[name="' + name + '"]:checked').data('id'));
                                // placeTypeNewList.push({
                                //     value: $('input[name="'+name+'"]:checked').data('id'),
                                //     displayName: $('input[name="'+name+'"]:checked').data('name'),
                                // })
                            }
                        });
                        let belongings = [];
                        if (Utils.IsNotNull(_vm.belongingsName) && Utils.IsNotNull(_vm.belongingsQty)) {
                            if (_vm.belongingsName.replace(/[，]/g, ',').includes(',') && _vm.belongingsQty.replace(/[，]/g, ',').includes(',')) {
                                let nameList = _vm.belongingsName.split(',');
                                let qtyList = _vm.belongingsQty.split(',');
                                if (nameList.length != qtyList.length) {
                                    return $.toptip(`随身物品名称与数量不对应!`, 'warning');
                                }
                                belongings = [];
                                for (let i = 0; i < nameList.length; i++) {
                                    belongings.push({
                                        name: nameList[i],
                                        qty: qtyList[i],
                                    });
                                }
                            } else {
                                belongings = [];
                                belongings.push({
                                    name: _vm.belongingsName,
                                    qty: _vm.belongingsQty,
                                });
                            }
                        }
                        let params = {
                            type: 1, // 人员入厂
                            destFarm: {
                                id: _vm.farmOrg.id,
                                name: _vm.farmOrg.name,
                            },
                            planDate: _vm.isolationDate,
                            deliverySeq: 0,
                            person: {
                                name: _vm.name,
                                gender: _vm.sex == '男' ? 1 : 2,
                                phoneNumber: _vm.phoneNum,
                                numCode: _vm.numCode,
                                isolationDate: _vm.isolationDate,
                                tripDetail: _vm.trip,
                                belongings: belongings,
                                placeType: placeTypeNewList.join(','),
                                departTime: _vm.departTime,
                                attachments: _vm.attaches.join(','),
                                sourceFarm: {
                                    id: _vm.departureFactory.id || '',
                                    name: _vm.departureFactory.name || '',
                                },
                                sourceDepartTime: _vm.departureDate || '',
                                unionId: openId,
                                openId: openId,
                            },
                            materials: null,
                            car: null,
                            remark: _vm.remark,
                            billStatus: 1, // 保存传1 保存并提交传2
                        };
                        // 保存
                        if (type == 1) {
                            InboundPlanApi.addEntryplans(params).then(
                                (res) => {
                                    $.toptip('人员入厂计划保存成功！', 'success');
                                    setTimeout(function () {
                                        location.href = `./inboundplanlist.html`;
                                    }, 1000);
                                },
                                (err) => {
                                    $.toptip(err.responseJSON?.msg, 'error');
                                },
                            );
                        }
                        // 保存并提交
                        else if (type == 2) {
                            params.billStatus = 2;
                            InboundPlanApi.addEntryplans(params).then(
                                (res) => {
                                    InboundPlanApi.submitPerInPlan(res).then((res1) => {
                                        $.toptip('人员入厂计划保存提交成功！', 'success');
                                        setTimeout(function () {
                                            location.href = `./inboundplanlist.html`;
                                        }, 1000);
                                    });
                                },
                                (err) => {
                                    $.toptip(err.responseJSON?.msg, 'error');
                                },
                            );
                        }
                    },
                },
            ],
        });
    };

    //TODO :初始化下拉框内容
    const initSelectValue = async () => {
        // 获取所有猪厂
        await InboundPlanApi.getSubdata('LIVESTOCK-FARMS').then((res) => {
            let info = JSON.parse(res);
            $('#farmOrg,#departureFactory')
                .empty()
                .select2({
                    placeholder: '请选择农厂...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: info.map((item) => {
                        return {
                            id: item.Id,
                            text: `${item.Name}`,
                            name: item.Name,
                        };
                    }),
                });
            $('#farmOrg,#departureFactory').setSelectValue();
        });
        // 选择 目的地
        $('#farmOrg').on('select2:select', async function (e) {
            _vm.farmOrg.id = $('#farmOrg').select2('data')[0].id;
            _vm.farmOrg.name = $('#farmOrg').select2('data')[0].name;
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });
        // 选择 出发厂
        $('#departureFactory').on('select2:select', async function (e) {
            _vm.departureFactory.id = $('#departureFactory').select2('data')[0].id;
            _vm.departureFactory.name = $('#departureFactory').select2('data')[0].name;
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        // 入厂计划场所类型
        await requestDict(DictionaryType.INBOUNDPLANPLACE_TYPE).then((res) => {
            placeTypeList = [];
            res.data.forEach((item) => {
                inboundPlanPlaceInfo[item.value] = item.displayName;
                placeTypeList.push(item.value);
            });
            $('#placeType')
                .empty()
                .select2({
                    placeholder: '请选择场所类型...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: res.data.map((item) => {
                        return {
                            ...item,
                            id: item.value,
                            text: `${item.displayName}`,
                        };
                    }),
                });
            $('#placeType').setSelectValue();
            $('#placeTypeDiv').empty().append(addPlaceTypeTemplate(res.data));
        });
    };

    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 10) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $.showLoading('上传中...');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            },
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 10) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };

    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile)
            .then((res) => {
                if (res.isSucceed) {
                    let _list = _vm.images;
                    _list.push({
                        id: $('#uploaderFiles li').length,
                        imageId: res.data,
                        url: upFiles.url,
                        name: newName,
                    });
                    _vm.attaches.push(res.data);
                    $('#uploaderFiles li').each(function (i) {
                        $(this).attr('data-id', _vm.images[i].id);
                        $(this).attr('data-image-id', _vm.images[i].imageId);
                        $(this).attr('data-name', _vm.images[i].name);
                        $(this).attr('data-suffix', _vm.images[i].type);
                        $(this).attr('data-url', _vm.images[i].url);
                        $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                    });
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                    $.hideLoading();
                    $.closeModal();
                }
            })
            .catch((res) => {
                $('#uploaderFiles li')
                    .eq($('#uploaderFiles li').length - 1)
                    .remove();
                _vm.uploadCount = --_vm.uploadCount;
                $.toptip(res.msg, 'error');
            })
            .finally((_) => {
                $.hideLoading();
                $.closeModal();
            });
    };
    // 编辑回写
    const _images = async (file) => {
        let _imag = file.split(',');
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then((_res) => {
                    let _list = _vm.images;
                    _list.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (['jpg', 'jpeg', 'png', 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 10) {
                $('.weui-uploader__input-box').hide();
            }
            _vm.uploadCount = _sun;
        }
    };

    // 时间选择器
    const pickIsolationDate = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                // let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                // _vm.isolationDate = moment(new Date(value)).format('YYYY-MM-DD');
                _vm.isolationDate = result.map((item) => item.value).join('-');
            },
        });
    };

    // 时间选择器
    const pickDepartureDate = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                // let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                // _vm.departureDate = moment(new Date(value)).format('YYYY-MM-DD');
                _vm.departureDate = result.map((item) => item.value).join('-');
            },
        });
    };

    // 时间选择器
    const pickPlanDate = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                // let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                // _vm.planDate = moment(new Date(value)).format('YYYY-MM-DD');
                _vm.planDate = result.map((item) => item.value).join('-');
            },
        });
    };
    // 时间选择器
    const pickDepartTime = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                // let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                // _vm.departTime = moment(new Date(value)).format('YYYY-MM-DD');
                _vm.departTime = result.map((item) => item.value).join('-');
            },
        });
    };

    // 获取地址栏的 参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat('...');
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串；
        if (str_length < len) {
            return str;
        }
    };
})(window, document, jQuery);
